import 'package:blurb/common/models/share.dart';
import 'package:blurb/common/services/share_service.dart';
import 'package:mobx/mobx.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/material.dart';

// 包含生成的代码部分
part 'share_store.g.dart';

// 使用命令生成代码：flutter packages pub run build_runner build
class ShareStore = _ShareStore with _$ShareStore;

abstract class _ShareStore with Store {
  @observable
  List<Share> shares = [];
  
  @observable
  bool isLoading = false;

  @action
  Future<void> init() async {
    isLoading = true;
    try {
      // 初始化默认分享
      await ShareService.initDefaultShares();
      // 加载所有分享
      shares = await ShareService.getAllShares();
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<List<Share>> getUserShares(int userId) async {
    isLoading = true;
    try {
      return await ShareService.getUserShares(userId);
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<bool> addShare(String description, String picture, int userId) async {
    return addShareWithPictures(description, picture, userId);
  }
  
  // 支持多张图片的公开方法
  Future<bool> addShareWithPictures(String description, String picture, int userId, {List<String>? pictures}) async {
    isLoading = true;
    try {
      if (description.isEmpty || picture.isEmpty) {
        Fluttertoast.showToast(
          msg: "description or picture is empty",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }

      // 获取所有分享，确定新分享ID
      final allShares = await ShareService.getAllShares();
      final newShareId = allShares.isEmpty ? 1 : allShares.map((share) => share.id).reduce((a, b) => a > b ? a : b) + 1;

      // 创建新分享
      final newShare = Share(
        id: newShareId,
        description: description,
        picture: picture,
        pictures: pictures,
        time: DateTime.now().toIso8601String(),
        userId: userId,
      );

      // 添加新分享
      final success = await ShareService.addShare(newShare);
      if (success) {
        // 更新本地列表
        shares = [...shares, newShare];
        Fluttertoast.showToast(
          msg: "share success",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        return true;
      } else {
        Fluttertoast.showToast(
          msg: "share failed",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<bool> updateShare(int shareId, String description, String picture) async {
    isLoading = true;
    try {
      // 查找要更新的分享
      final shareIndex = shares.indexWhere((share) => share.id == shareId);
      if (shareIndex == -1) {
        Fluttertoast.showToast(
          msg: "share not found",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }

      final originalShare = shares[shareIndex];
      
      // 创建更新后的分享对象
      final updatedShare = Share(
        id: shareId,
        description: description,
        picture: picture,
        time: originalShare.time, // 保持原有时间
        userId: originalShare.userId,
      );
      
      // 更新分享
      final success = await ShareService.updateShare(updatedShare);
      if (success) {
        // 更新本地列表
        shares[shareIndex] = updatedShare;
        shares = [...shares]; // 触发重新渲染
        
        Fluttertoast.showToast(
          msg: "update success",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        return true;
      } else {
        Fluttertoast.showToast(
          msg: "update failed",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }
    } finally {
      isLoading = false;
    }
  }
  
  @action
  Future<bool> deleteShare(int shareId) async {
    isLoading = true;
    try {
      final success = await ShareService.deleteShare(shareId);
      if (success) {
        // 更新本地列表
        shares = shares.where((share) => share.id != shareId).toList();
        
        Fluttertoast.showToast(
          msg: "delete success",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        return true;
      } else {
        Fluttertoast.showToast(
          msg: "delete failed",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }
    } finally {
      isLoading = false;
    }
  }
  
  @action
  Future<void> refreshShares() async {
    isLoading = true;
    try {
      shares = await ShareService.getAllShares();
      // 按时间倒序排序，最新的在前面
      shares.sort((a, b) => DateTime.parse(b.time).compareTo(DateTime.parse(a.time)));
    } finally {
      isLoading = false;
    }
  }
} 